package com.gupaoedu.demo.serialize;

import java.io.*;

/**
 * <p>
 *
 * </p>
 *
 * @author Nicky
 * @since 2019-07-20
 */
public class JavaSerialize implements ISerialize {

    @Override
    public <T> byte[] serialize(T object) {
        ByteArrayOutputStream byteArrayOutputStream =
                new ByteArrayOutputStream();

        try {
            ObjectOutputStream objectOutputStream =
                    new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(object);
            return  byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new byte[0];
    }

    @Override
    public <T> T deserialize(byte[] bytes,Class<T> claz) {
        ByteArrayInputStream byteInputStream =
                new ByteArrayInputStream(bytes);
        try {
            ObjectInputStream objectInputStream =
                    new ObjectInputStream(byteInputStream);
            return (T) objectInputStream.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        return null;
    }
}
